import axios from 'axios'
import Session from '../utils/Session'
import { message } from 'antd';
import md5 from '../assets/js/md5.js'
export default {
    inputFilfter(value, status) {
        switch (status) {
          case 1: //只能输入字母和数字
            return value.replace(/[^\w]/g, '');
            break;
          case 2: //只能输入数字
            return value.replace(/[^\d]/g, '');
            break;
          case 3: //判断固话，只能输入+-和数字
            return value.replace(/[^\d\-\+]/g, '');
            break;    
          case 4: //只能输入数字，2位有效小数
            value = value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符  
            value = value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的  
            value = value.replace(".","$#$").replace(/\./g,"").replace("$#$","."); 
            value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数  
            if(value.indexOf(".")< 0 && value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额 
                value= parseFloat(value); 
            }           
            return value;                
            break;               
        }
      },    
      getNowFormatDate(needYear = false) { //为导出的文件添加日期
        var date = new Date();
        var seperator1 = "";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
    
        var currentdate = needYear == true ? year + month + seperator1 + strDate : month + seperator1 + strDate;
        return currentdate;
      },      
      sessionStorage:{
        storage:window.sessionStorage,
        getItem: function (key){         
          let value = this.storage.getItem(key);        
          if (value === null){
              return false;
          }
          if (value && value.substring(0, 1) === "{" || value.substring(0, 1) == "[") {  // 判断字符串是否是对象或则数组结构
              value = JSON.parse(value);  //将字符串转成json
          }
          return value
        },
        setItem: function (key,value){
            if(this.getType(value) === 'Object' || this.getType(value) === 'Array') {            
                value = JSON.stringify(value);
            }
            this.storage.setItem(key, value);
        },
        // 删除项
        removeItem: function (key) {
            this.getItem(key) && this.storage.removeItem(key);
        },
        //  清空
        clear: function () {
          this.storage.clear(); // 清空本地存储
        },      
        getType:(object) => {
          /**
           * 方法来源：prototype.js
           * getType(5); // => "Number"
           * getType({}); // => "Object"
           * getType(/foo/); // => "RegExp"
           * getType(''); // => "String"
           * getType(true); // => "Boolean"
           * getType([]); // => "Array"
           * getType(undefined); // => "Window"
           * getType(Element); // => "Constructor"
           **/
          return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
      }          
    }, 
    localStorage:{
      storage:window.localStorage,
      getItem: function (key){         
        let value = this.storage.getItem(key);        
        if (value === null){
            return false;
        }
        if (value && value.substring(0, 1) === "{" || value.substring(0, 1) == "[") {  // 判断字符串是否是对象或则数组结构
            value = JSON.parse(value);  //将字符串转成json
        }
        return value
      },
      setItem: function (key,value){
          if(this.getType(value) === 'Object' || this.getType(value) === 'Array') {            
              value = JSON.stringify(value);
          }
          this.storage.setItem(key, value);
      },
      // 删除项
      removeItem: function (key) {
          this.getItem(key) && this.storage.removeItem(key);
      },
      //  清空
      clear: function () {
        this.storage.clear(); // 清空本地存储
      },      
      getType:(object) => {
        /**
         * 方法来源：prototype.js
         * getType(5); // => "Number"
         * getType({}); // => "Object"
         * getType(/foo/); // => "RegExp"
         * getType(''); // => "String"
         * getType(true); // => "Boolean"
         * getType([]); // => "Array"
         * getType(undefined); // => "Window"
         * getType(Element); // => "Constructor"
         **/
        return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
      }          
    },     
    arrayEquals(array1,array2){//对比数组是否相等      
      Array.prototype.equals = function(array) {
        // if the other array is a falsy value, return
        if(!array)
          return false;
  
        // compare lengths - can save a lot of time 
        if(this.length != array.length)
          return false;
  
        for(var i = 0, l = this.length; i < l; i++) {
          // Check if we have nested arrays
          if(this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if(!this[i].equals(array[i]))
              return false;
          } else if(this[i] != array[i]) {
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;
          }
        }
        return true;
      }
      return array1.equals(array2)
    },
    getNowTime(){//获取服务器年月日时分秒
      //判断缓存中是否有时间戳，有则通过算法自行增加
      if(sessionStorage.getItem('timestampGap') && sessionStorage.getItem('timestampGap') != 'NaN'){
        let timestamp = new Date(Number(new Date().valueOf() + Number(sessionStorage.getItem('timestampGap'))+""));      
  
        //获取当前年月日时分秒
        var date = new Date(timestamp);
  
        var year = date.getFullYear();
        
        var month = date.getMonth()+1<10?'0'+(date.getMonth()+1):date.getMonth()+1;
        var day = date.getDate()<10?"0"+date.getDate():date.getDate();
        var hour = date.getHours()<10?"0"+date.getHours():date.getHours();
        var minute = date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes();
        var second = date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds();
  
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;       
  
      }else{      
        var axios_instance = axios.create({
          transformRequest: [function (data) {
            data = JSON.stringify(data);
            return data;
          }],
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          responseType: 'json'
        });
    
        axios_instance.post(process.env.Text[3]+"/center/sys/timestamp/get", {}).then(function (res) {
          //算出服务器时间和本地时间的相差值
          if (res && res.data && res.data.data) {
            let _timestampGap = Number(new Date(res.data.data).valueOf()) - Number(new Date().valueOf());
    
            sessionStorage.setItem('timestampGap',_timestampGap);
          }
          // return res.data.data;
        }).catch(function (error) { 
          console.log(' ========= error = ', error)       
          message.error(error.data ? error.data.msg : '服务器开小差了,请稍后重试~~' )      
        }); 
      }
         
    },
    getSign(data){//获取验证sign 
      let _nonce = sessionStorage.getItem('userInfo') ? JSON.parse(sessionStorage.getItem('userInfo')).nonce : "";
  
      let _data =  data instanceof Object ? data : typeof data == 'string' ? JSON.parse(data) : false;
  
      if(_data){
        //过滤对象中的空字符串，对象和数组和sign
        for(let i in _data){
          if(_data[i] === "" || _data[i] === undefined || _data[i] === null || (typeof _data[i] == 'object') || i == 'sign'){
            delete _data[i]
          }
        }
  
        _data = this.sort_ASCII (_data);
        
        let _s = "";
        for(let i in _data){
            _s+=`&${i}=${_data[i]}`      
        }
  
        console.log(`${this.getAppSecret()}${_s.substring(1)}${_nonce}`)
  
        return md5(`${this.getAppSecret()}${_s.substring(1)}${_nonce}`).toUpperCase();
      }
      
    },
    getAppKey(){
      return Session.centerUrl.includes('24') || Session.centerUrl.includes('25')?"XS4MH4J5R9RQF0VBPS":"MSEDU#MANHATTAN#WEB";
    },
    getAppSecret(){
      return Session.centerUrl.includes('24') || Session.centerUrl.includes('25')?"VGPW3H5NQGZ2ZZV3D6KKR6HBKE5HR3OCG7I6":"WSSTBYW4LUNC8BSLZTWLXGVCYHDOJYYAB7Q2";
    },
    getSafeObj(data){
      // 获取安全验证的对象
      let _data = Object.assign({},data,{
        appKey:this.getAppKey(),
        timestamp:this.getNowTime()      
      })
      return {
        appKey:this.getAppKey(),
        sign:this.getSign(_data),
        timestamp:this.getNowTime()      
      }
    },
    sort_ASCII(obj){//ascii排序
      var arr = new Array();
      var num = 0;
      for (var i in obj) {
        arr[num] = i;
        num++;
      }
      var sortArr = arr.sort();
      var sortObj = {};
      for (var i in sortArr) {
        sortObj[sortArr[i]] = obj[sortArr[i]];
      }
      return sortObj;
    },
    //获取url上的参数
    getQueryString(url,name){
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
      var r = url.substr(1).match(reg);
      if (r != null) {
          return unescape(r[2]);
      }
      return null;
  },
  getNewObj(data) {
    //深复制对象或者数组
    if (typeof data == "object") {
        let _obj = {};
        _obj = JSON.parse(JSON.stringify(data)); //data是父组件传递的对象
        return _obj;
    } else {
        let _obj;
        [_obj] = [data];
        return _obj;
    }
  },  
  getUrlQuery(name, search){
    search = search ||  window.location.search.substr(1) || window.location.hash.split("?")[1];
    let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    if(!search){
      return null
    }
    let r = search.match(reg);
    if (r != null) return  unescape(r[2]); return null;
  }
}